package edu.wuster.blog.service.impl;

import edu.wuster.blog.entity.Blogpart;
import edu.wuster.blog.exception.MyException;
import edu.wuster.blog.mapper.BlogpartMapper;
import edu.wuster.blog.mapper.CollectMapper;
import edu.wuster.blog.service.BlogpartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;


@Slf4j
@Service
public class BlogpartServiceImpl implements BlogpartService {
    @Autowired
    private BlogpartMapper blogpartMapper;

    @Autowired
    private CollectMapper collectMapper;

    @Override
    public Blogpart selectById(Integer id) {
        //判断博客是否存在
        if (blogpartMapper.selectById(id) == null) {
            log.info("该博客不存在");
            throw new MyException("该博客不存在");
        }
        log.info("博客（id：{}）查看", id);
        Blogpart blogpart = blogpartMapper.selectById(id);
        return blogpart;
    }

    //新建博客并保存为草稿/或直接发布，由前端传入#state来区分
    @Override
    public Integer addBlogpartSave(Blogpart blogpart) {
        blogpart.setCreateTime(LocalDateTime.now());
        blogpartMapper.addBlogpartSave(blogpart);
        return blogpart.getId();
    }

    @Override
    public void deleteBlogpart(Integer id){

        if (blogpartMapper.selectById(id) == null) {
            log.info("被删除博客不存在");
            throw new MyException("被删除博客不存在");
        }

        Integer blogId = id;

        //将收藏了此博客的记录删除
        collectMapper.deleteByBlogId(blogId);

        blogpartMapper.deleteBlogpart(id);

    }

    //管理员审核及下架的状态更改，由前端传入目标状态来区分
    @Override
    public void resetById(Blogpart blogpart){

        if (blogpartMapper.selectById(blogpart.getId()) == null) {
            log.info("待修改状态博客不存在");
            throw new MyException("待修改状态博客不存在");
        }

        log.info("博客（id：{}）修改状态", blogpart.getId());

        blogpartMapper.resetById(blogpart);

    }

    @Override
    public void addLike(Integer id){

        if (blogpartMapper.selectById(id) == null) {
            log.info("点赞博客不存在");
            throw new MyException("点赞博客不存在");
        }

        blogpartMapper.addLike(id);

        log.info("点赞成功");

    }

    @Override
    public void blogModify(Blogpart blogpart){
        log.info("修改博客");
        if (blogpartMapper.selectById(blogpart.getId()) == null) {
            log.info("修改的博客不存在");
            throw new MyException("修改的博客不存在");
        }
        blogpart.setCreateTime(LocalDateTime.now());
        blogpartMapper.blogModify(blogpart);

        log.info("博客修改成功");


    }


}